package com.hmdp.utils;

import com.aliyun.dm20151123.Client;
import com.aliyun.dm20151123.models.SingleSendMailRequest;
import com.aliyun.dm20151123.models.SingleSendMailResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.hmdp.properties.AliMailProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 通过邮件推送服务发送验证码
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SendMessageCode {

    private final AliMailProperties aliMailProperties;

    /**
     * 发送邮件
     *
     * @param toAddress
     * @param textBody
     */
    public SingleSendMailResponse sendMail(String toAddress, String textBody) throws Exception {
        log.info("发送邮件到：{}，内容：{}", toAddress, textBody);

        Client client = new Client(
                new Config()
                        .setAccessKeyId(aliMailProperties.getAccessKeyId())
                        .setAccessKeySecret(aliMailProperties.getSecret())
                        .setEndpoint(aliMailProperties.getEndpoint()));
        SingleSendMailRequest singleSendMailRequest = new SingleSendMailRequest()
                .setAccountName(aliMailProperties.getAccountName())
                .setTagName(aliMailProperties.getTagName())
                .setAddressType(aliMailProperties.getAddressType())
                .setReplyToAddress(aliMailProperties.getReplyToAddress())
                .setToAddress(toAddress)
                .setSubject(aliMailProperties.getSubject())
                .setHtmlBody("<h2>您正在登录黑马点评网站，验证码为：" + textBody + "</h2>")
                .setFromAlias(aliMailProperties.getFromAlias())
                .setReplyAddress(aliMailProperties.getReplyAddress())
                .setReplyAddressAlias(aliMailProperties.getReplyAddressAlias());
        RuntimeOptions runtime = new RuntimeOptions();
        // 复制代码运行请自行打印 API 的返回值
        SingleSendMailResponse singleSendMailResponse = client.singleSendMailWithOptions(singleSendMailRequest, runtime);
        return singleSendMailResponse ;
    }
}
